package com.da.javatest.mock;

import com.da.javatest.util.MyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.stereotype.Component;

/**
 * @author: chenlida
 * @date: 2020/06/07 09:58
 * @description:
 */
@Component
public class MyUtilProxy2 implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MyUtil) {
            return mockMyUtil();
        }
        return bean;
    }

    private Object mockMyUtil() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(MyUtil.class);
        enhancer.setCallback((MethodInterceptor)(o, method, objects, methodProxy) -> {
            if (StringUtils.equals(method.getName(), "getName2")) {
                return "代理：JokerDa.";
            }
            return methodProxy.invokeSuper(o, objects);
        });
        //返回被代理的对象
        return enhancer.create();
    }

}
